<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        @returnBack="$emit('returnModify')"
      >
        <template v-slot:full-button>
          <el-button :disabled="!canSave" @click="saveAndSubmit()" v-if="!orderId && $permission('withTableRecordOrder:saveAndSubmit')">保存并提交</el-button>
          <el-button :disabled="!canSave" @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
            </page-form>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <page-filter :filter-list="filterInfo.list">
              <template v-slot:filter-addProduct>
                <el-button :disabled="!canAddProduct" @click="addProduct"
                  >添加产品</el-button
                >
              </template>
              <template v-slot:filter-removeProduct>
                <el-button
                  :disabled="!canRemoveProduct"
                  @click="removeProduct()"
                  >删除产品</el-button
                >
              </template>
              <template v-slot:filter-productCodeScan>
                <ScanInputBox
                  :query="scanInfo.query"
                  :api="scanInfo.api"
                  :selectScanInfo="selectScanInfo"
                  :disabled="!canAddProduct"
                  @callback="onCallBackScanData"
                />
              </template>
            </page-filter>
            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <page-table
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :summary="true"
                  :summary-field-list="tableInfo.summaryFieldList"
                  :tab-index="true"
                  :checkbox="true"
                  :isRowClickSelect="true"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-qty="scope">
                    <template v-if="!tableInfo.isSysGroup">
                      <el-form-item
                        v-if="
                          scope.row.codeType === 1 ||
                          scope.row.codeType === 4 ||
                          (scope.row.codeType === 2 && !scope.row.uniqueCode) ||
                          (scope.row.codeType === 3 &&
                            !scope.row.factoryMainCode) ||
                          (scope.row.codeType === 3 &&
                            !scope.row.factorySubCode)
                        "
                        class="margin-bottom"
                      >
                        <div class="page-table-input-number-wrapper">
                          <div class="page-table-input-number-left">
                            <div class="page-table-input-number-item">
                              <el-form-item
                                :prop="`data.${scope.$index}.largeUnitQty`"
                                :rules="
                                  scope.$index >= 0
                                    ? [
                                        {
                                          validator: $validate.positiveAndZero,
                                          trigger: 'blur',
                                        },
                                      ]
                                    : []
                                "
                              >
                                <el-input-number
                                  v-model.lazy="scope.row.largeUnitQty"
                                  style="width: 100%; margintop: 18px"
                                  clearable
                                  controls-position="right"
                                  :precision="
                                    scope.row.qtyOperateMode === 0 ||
                                    scope.row.qtyOperateMode === 2
                                      ? 0
                                      : systemConfig.qty_show_precision
                                  "
                                  :min="0"
                                  :max="largeMax(scope.row)"
                                  @change="
                                    changeLarge(
                                      $event,
                                      scope.row,
                                      `data.${scope.$index}.largeUnitQty`
                                    )
                                  "
                                />
                              </el-form-item>
                              <div class="page-table-input-number-item-unite">
                                {{ scope.row.unitName }}
                              </div>
                            </div>
                            <div
                              v-if="
                                scope.row.unitConvertCoefficient > 1 &&
                                scope.row.qtyOperateMode === 2
                              "
                              class="page-table-input-number-item"
                            >
                              <el-form-item>
                                <el-input-number
                                  v-model.lazy="scope.row.smallUnitQty"
                                  style="width: 100%; margintop: 18px"
                                  clearable
                                  controls-position="right"
                                  :precision="0"
                                  :min="0"
                                  :max="smallMax(scope.row)"
                                />
                              </el-form-item>
                              <div class="page-table-input-number-item-unite">
                                {{ scope.row.calcUnitName }}
                              </div>
                            </div>
                          </div>
                          <div
                            v-if="scope.row.qtyOperateMode === 2"
                            class="page-table-input-number-right"
                          >
                            {{ $fn.qtyFormatter(scope.row.qty) }}
                          </div>
                        </div>
                      </el-form-item>
                      <span
                        v-else-if="
                          scope.row.codeType === 2 || scope.row.codeType === 3
                        "
                        >{{ $fn.qtyFormatter(scope.row.qty) }}</span
                      >
                    </template>
                    <span v-else>{{ $fn.qtyFormatter(scope.row.qty) }}</span>
                  </template>
                  <template v-slot:col-batchNumber="scope">
                    <el-input
                      v-model="scope.row.batchNumber"
                      :maxlength="25"
                      @change="changeData($event, scope.row, scope.$index)"
                      @input="(e) => (scope.row.batchNumber = validSe(e))"
                    />
                  </template>
                  <template v-slot:col-productionDate="scope">
                    <el-date-picker
                      v-model="scope.row.productionDate"
                      value-format="YYYY-MM-DD"
                      :disabled-date="productionTimePickerOptions.disabledDate"
                      @change="changeData($event, scope.row, scope.$index)"
                    />
                  </template>
                  <template v-slot:col-validityDate="scope">
                    <el-date-picker
                      v-model="scope.row.validityDate"
                      value-format="YYYY-MM-DD"
                      :disabled-date="validityTimePickerOptions.disabledDate"
                      @change="changeData($event, scope.row, scope.$index)"
                    />
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <SelectDepotStorage
      v-if="selectDepotStorageInfo.visible"
      v-model:show-dialog="selectDepotStorageInfo.visible"
      :query="selectDepotStorageInfo.query"
      :left-table-key="selectDepotStorageInfo.leftTableKey"
      :right-table-key="selectDepotStorageInfo.rightTableKey"
      :api="selectDepotStorageInfo.api"
      :exclude-query-list="selectDepotStorageInfo.excludeQueryList"
      :show-price="$permission('withTableRecordOrder:price')"
      @callback="selectDepotStorageCallBack"
    />
    <select-individual
      v-if="individualInfo.visible"
      v-model:visible="individualInfo.visible"
      v-model:left-query-obj="individualInfo.leftQuery"
      v-model:right-query-obj="individualInfo.rightQuery"
      v-model:info-list="individualInfo.productInfo"
      :request-right-list="!!orderId"
      v-model:right-api="individualInfo.rightApi"
      v-model:left-api="individualInfo.leftApi"
      v-model:right-vo="individualInfo.rightVo"
      :mapsId="individualInfo.mapsId"
      :mapsIdReversal="individualInfo.mapsIdReversal"
      left-table-key="withTableRecordOrderModifyByAccepSingleLeft-com.slip.spd.entity.vo.withtable.WithTableAcceptOrderDetailVO"
      :show-price="$permission('withTableRecordOrder:price')"
      :scan-info="scanInfo"
      @callbackSacn="callbackSacn"
      @callback="selectedProductDetails"
    />
  </div>
</template>

<script setup name="OtherExportOrderModify">
import PageForm from '@/components/PageForm/index'
import PageTable from '@/components/PageTable/index'
import PageFilter from '@/components/PageFilter/index'
import SelectDepotStorage from './selectDepotStorage'
import selectIndividual from '../components/individual'
import ScanInputBox from '../components/ScanInputBoxAccept'
import {
  getWithTableRecordOrderById,
  getWithTableRecordOrderDetailAll,
  getWithTableAcceptOrderDetailPage,
  createWithTableRecordOrder,
  createWithTableRecordOrderAndSave,
  updateWithTableRecordOrder,
  withTableAcceptOrderDetailScan,
} from '@/api/withTable.js'
import { getCustomizeSetting } from '@/api/customize'
import {
  setDisableTime,
  _getCurrentFiscalPeriod,
} from '@/common/js/dateOperation'
let pickerOptions = {
  disabledDate(time) {
    return time.getTime() > Date.now() // 选当前时间之后的时间
  },
}

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))
const productionTimePickerOptions = reactive({
  disabledDate(time) {
    return time.getTime() > Date.now() - 8.64e6
  },
})
const validityTimePickerOptions = reactive({
  disabledDate(time) {
    return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
  },
})
const props = defineProps([
  'visible',
  'title',
  'orderId',
  'acceptOrderNo',
  'acceptOrderId',
  'supplierName',
  'supplierId',
])

const formRefs = ref('')
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const scanInfo = reactive({
  api: withTableAcceptOrderDetailScan,
  query: {
    queryMap: {},
    customizeUserVO: {},
    queryParams: {
      orderId: props.acceptOrderId,
      idNotIn: '',
      // validateExpire: false
    },
  },
})
//表单相关
const formInfo = reactive({
  ref: null,
  data: {
    supplierName: props.supplierName,
    supplierId: props.supplierId,
    acceptOrderNo: props.acceptOrderNo,
    acceptOrderId: props.acceptOrderId,
  },
  fieldList: [
    {
      label: '手术名称',
      value: 'surgeryName',
      type: 'input',
    },
    {
      label: '手术时间',
      value: 'surgeryTime',
      type: 'date',
      dateType: 'datetime',
      TimePickerOptions: pickerOptions,
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
    },
    {
      label: '手术地点',
      value: 'surgeryPlace',
      type: 'input',
    },
    {
      label: '供应商',
      value: 'supplierName',
      type: 'input',
      disabled: true,
    },
    {
      label: '验收单号',
      value: 'acceptOrderNo',
      type: 'input',
      disabled: true,
    },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'date',
      clearable: false,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      maxlength: 200,
    },
  ],
  rules: {
    surgeryName: [
      { required: true, message: '请输入手术名称', trigger: 'blur' },
    ],
    surgeryPlace: [
      { required: false, message: '请输入手术地点', trigger: 'blur' },
    ],
    surgeryTime: [
      { required: true, message: '请选择手术时间', trigger: 'change' },
    ],
    businessDate: [
      { required: true, message: '请选择业务日期', target: 'blur' },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
  },
  list: [
    { type: 'slot', value: 'addProduct' },
    { type: 'slot', value: 'removeProduct' },
    { type: 'slot', value: 'productCodeScan' },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  map: new Map(),
  isSysGroup: true, //新增修改页是否有后端合并
  sysGroup: [], //新增修改页后端合并项
  selections: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '个体操作',
        event: _selectIndividual,
        show: true,
        ifRender: ifRenderValue,
      },
      {
        label: '删除',
        event: removeProduct,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
const selectScanInfo = reactive({
  //库存产品
  api: getWithTableAcceptOrderDetailPage,
  leftTableKey:
    'withTableRecordOrderModifyQueryProductLeft-com.slip.spd.entity.vo.withtable.WithTableAcceptOrderDetailVO',
  rightTableKey:
    'withTableRecordOrderModifyQueryProductright-com.slip.spd.entity.vo.withtable.WithTableAcceptOrderDetailVO',
  visible: false,
  excludeQueryList: [], //库存产品左侧过滤配置
  scanData: [],
  showPrice: proxy.$permission('withTableRecordOrder:price'),
  query: {
    orderId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: props.acceptOrderId,
    },
    generalProductCategory: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: 0,
    },
    queryParams: { availableCalcQtyGt: 0 },
  },
})
const selectDepotStorageInfo = reactive({
  //库存产品
  api: getWithTableAcceptOrderDetailPage,
  leftTableKey:
    'withTableRecordOrderModifyQueryProductLeft-com.slip.spd.entity.vo.withtable.WithTableAcceptOrderDetailVO',
  rightTableKey:
    'withTableRecordOrderModifyQueryProductright-com.slip.spd.entity.vo.withtable.WithTableAcceptOrderDetailVO',
  visible: false,
  scanData: [],
  showPrice: proxy.$permission('withTableRecordOrder:price'),
  query: {
    orderId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: props.acceptOrderId,
    },
    generalProductCategory: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: 0,
    },
    queryParams: { detailId: '', availableCalcQtyGt: 0 },
  },
})
const individualInfo = reactive({
  visible: false,
  selectObj: {}, //库存产品弹窗左边后端合并项
  productInfo: {}, //个体操作的当前这条数据
  leftQuery: {}, //个体弹窗左边数据查询条件
  rightQuery: {}, //个体弹窗右边数据查询条件
  rightApi: getWithTableRecordOrderDetailAll, //个体弹窗右边数据接口
  leftApi: getWithTableAcceptOrderDetailPage, //个体弹窗左边数据接口
  rightVo: {}, //个体弹窗右边配置
  mapsId: {},
  mapsIdReversal: {},
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

const canSave = computed(() => {
  return tableInfo.data.length
})
const canAddProduct = computed(() => {
  return true
})
const canRemoveProduct = computed(() => {
  return tableInfo.selections.length
})

watch(
  () => tableInfo.data,
  (val) => {
    if (val.length && !tableInfo.isSysGroup) {
      val.forEach((row) => {
        let smallUnitQty = parseFloat(row.smallUnitQty || 0)
        let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
        let largeUnitQty = parseFloat(row.largeUnitQty || 0)
        let calcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
          smallUnitQty
        )
        let qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
        row['calcQty'] = calcQty
        row['qty'] = qty
        row.sumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(calcQty, parseFloat(row.price)),
          unitConvertCoefficient
        )
        if (row.details && row.details.length) {
          row.details[0].qty = qty
          row.details[0].calcQty = calcQty
          row.details[0].largeUnitQty = largeUnitQty
          row.details[0].smallUnitQty = smallUnitQty
          row.details[0].sumAmount = row.sumAmount
        }
      })
    }
    scanInfo.query.queryParams.idNotIn = ''
    if (val.length) {
      let ids = val.map((item) => item.groupConcatDepotStockIds).toString()
      scanInfo.query.queryParams.idNotIn = ids
      console.log(ids)
    }
  },
  {
    deep: true,
  }
)

let obj = {
  qty: {
    label: '数量',
    value: 'qty',
    type: 'slot',
    minWidth: '250px',
  },
  price: {
    label: '单价',
    value: 'price',
    minWidth: '150px',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('withTableRecordOrder:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('withTableRecordOrder:price'),
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('withTableRecordOrder:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
  productionDate: {
    label: '生成日期',
    value: 'productionDate',
    type: 'slot',
    minWidth: '160px',
    hidden: true,
  },
  validityDate: {
    label: '失效日期',
    value: 'validityDate',
    minWidth: '160px',
    type: 'slot',
    hidden: true,
  },
  batchNumber: {
    label: '批号',
    value: 'batchNumber',
    type: 'slot',
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()
getInvdividualRightCustomize()

let disStartDate = ref('')
let disEndDate = ref('')
setDisableTime(formInfo.fieldList, disStartDate, disEndDate)
async function setBusinessDate() {
  formInfo.data.businessDate = await _getCurrentFiscalPeriod(
    formInfo.fieldList,
    proxy,
    disStartDate,
    disEndDate
  )
}
onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.ref]
  proxy.$nextTick(() => {
    if (!props.orderId) {
      formInfo.fieldList = formInfo.fieldList.filter(
        (item) => item.value !== 'orderNo'
      )
    }
  })
})
function changeData(evet, row, index) {
  //批号效期改变更新_id
  let item = tableInfo.data.filter((item, i) => i === index)
  const key =
    item.productId +
    '&' +
    item.batchNumber +
    '&' +
    item.validityDate +
    '&' +
    item.productionDate
  tableInfo.data[index] = {
    ...tableInfo.data[index],
    _id: key,
  }
}
function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.availableCalcQty / row.unitConvertCoefficient)
  } else {
    return row.availableQty
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(row.availableCalcQty / row.unitConvertCoefficient)
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.availableCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  let largeUnitQty = parseInt(row.availableCalcQty / row.unitConvertCoefficient)
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(
        row.availableCalcQty % row.unitConvertCoefficient
      )
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty
      }
    }
  }
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}
function ifRenderValue() {
  return tableInfo.isSysGroup
}
async function callbackSacn(data, oldInfo, callback) {
  //个体操作弹窗扫码回调
  let { mergeDetail, detail } = data
  mergeDetail[0].details = [detail]

  let key = []
  tableInfo.sysGroup.forEach((row) => {
    let obj = {}
    obj.columnName = row.columnName
    obj.asTbName = row.asTbName
    obj.value = mergeDetail[0][row.key]
    key.push(obj)
  })
  let newKey = JSON.stringify(key)
  if (tableInfo.map.has(newKey)) {
    if (
      oldInfo.groupConcatDepotStockIds.includes(detail.depotStockId.toString())
    ) {
      callback(true)
      return
    } else {
      if (oldInfo.key === newKey) {
        await setData(mergeDetail, newKey)
        await callback(false)
      } else {
        let value = tableInfo.map.get(newKey)
        if (
          await value.groupConcatDepotStockIds.includes(
            detail.depotStockId.toString()
          )
        ) {
          if ((await proxy.$fn.confirmRes()) === 'confirm') {
            await selectedProductDetails(oldInfo)
            await setData(
              mergeDetail,
              newKey,
              value.details && value.details.length
            )
            await callback(false)
          } else {
            await setData(
              mergeDetail,
              newKey,
              value.details && value.details.length
            )
            await callback(false)
          }
        } else {
          if ((await proxy.$fn.confirmRes()) === 'confirm') {
            await selectedProductDetails(oldInfo)
            await setData(mergeDetail, newKey)
            await callback(false)
          } else {
            await setData(mergeDetail, newKey)
            await callback(false)
          }
        }
      }
    }
  } else {
    if ((await proxy.$fn.confirmRes()) === 'confirm') {
      await selectedProductDetails(oldInfo)
      await setData(mergeDetail, newKey)
      await callback(false)
    } else {
      await setData(mergeDetail, newKey)
      await callback(false)
    }
  }
}

async function setData(data, newKey, type = false) {
  //个体操作弹窗扫码回调设置数据

  let newData
  if (!type) {
    let map = await proxy.$fn.getDepotStorage(
      data,
      tableInfo.sysGroup,
      tableInfo.map,
      getWithTableRecordOrderDetailAll,
      props.orderId,
      individualInfo.rightVo,
      'availableCalcQty',
      'depotStockId'
    )
    tableInfo.map = map
    tableInfo.data = [...map.values()]
    newData = map.get(newKey)
  } else {
    newData = tableInfo.map.get(newKey)
  }
  await getIndividualInfoQuery(newData)
}
async function onCallBackScanData(data, callback) {
  //扫码回调
  let { mergeDetail, detail } = data

  if (tableInfo.data && tableInfo.data.length) {
    let items = tableInfo.data.filter((row) => {
      if (detail.codeType === 2 || detail.codeType === 3) {
        let arr = proxy.$fn.splitArr(row.groupConcatDepotStockIds)
        let bool = arr.includes(detail.depotStockId.toString())
        return bool
      } else if (detail.codeType === 1 || detail.codeType === 4) {
        if (row.id === mergeDetail[0].id) {
          let num = proxy.$fn.Subtr(row.availableCalcQty, row.calcQty)
          if (num <= 1) {
            return row.calcQty === row.availableCalcQty
          }
        }
      }
    })
    if (items.length) {
      callback(true)
      return
    } else {
      callback(false)
    }
  }
  mergeDetail[0].details = [detail]
  mergeDetail[0].oldBatchNumber = proxy.$fn.deepClone(
    mergeDetail[0].batchNumber
  )
  mergeDetail[0].oldValidityDate = proxy.$fn.deepClone(
    mergeDetail[0].validityDate
  )
  mergeDetail[0].oldProductionDate = proxy.$fn.deepClone(
    mergeDetail[0].productionDate
  )
  let map = await proxy.$fn.getDepotStorage(
    mergeDetail,
    tableInfo.sysGroup,
    tableInfo.map,
    getWithTableRecordOrderDetailAll,
    props.orderId,
    individualInfo.rightVo,
    'availableCalcQty',
    'depotStockId'
  )
  tableInfo.map = map
  tableInfo.data = [...map.values()]
  console.log(tableInfo.data)
}
async function _selectIndividual(data) {
  //选择个体
  await getIndividualInfoQuery(data)
  individualInfo.visible = true
}
async function getIndividualInfoQuery(data) {
  // 设置个体操作参数
  for (let key in individualInfo.selectObj) {
    individualInfo.selectObj[key].value = data[key]
    if (key === 'batchNumber') {
      individualInfo.selectObj[key].value = data['oldBatchNumber']
    }
    if (key === 'validityDate') {
      individualInfo.selectObj[key].value = data['oldValidityDate']
    }
    if (key === 'productionDate') {
      individualInfo.selectObj[key].value = data['oldProductionDate']
    }
  }
  individualInfo.leftQuery.id = {
    queryType: 'NOT_IN',
    queryCategory: 'AND',
    value: data.groupConcatDepotStockIds,
  }
  individualInfo.leftQuery.productId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: data.productId,
  }
  individualInfo.leftQuery = {
    ...individualInfo.leftQuery,
    ...individualInfo.selectObj,
  }
  individualInfo.leftQuery.orderId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: props.acceptOrderId,
  }
  individualInfo.rightQuery.id = {
    queryType: 'IN',
    queryCategory: 'AND',
    value: data.groupConcatIds,
  }

  individualInfo.leftQuery.queryParams = {
    detailId: getDetailId(data),
  }

  individualInfo.rightQuery.orderId = {
    queryType: 'EQUALS',
    queryCategory: 'AND',
    value: props.orderId,
  }
  individualInfo.productInfo = data
}
function getDetailId(data) {
  let arr = []
  if (data.hasOwnProperty('details')) {
    let mapKey = {}
    if (data.mapKey) {
      mapKey = proxy.$fn.deepClone(data.mapKey)
      data.details.forEach((element) => {
        if (mapKey.hasOwnProperty(element.depotStockId)) {
          delete mapKey[element.depotStockId]
        }
      })
      arr = Object.values(mapKey).join(',')
    } else {
      let depotStockIds = data.details.map((element) => {
        return String(element.depotStockId)
      })
      let groupConcatDepotStockIds = depotStockIds
      let groupConcatIds = data.groupConcatIds.split(',')
      arr = getNotSame(groupConcatIds, groupConcatDepotStockIds)
      let _arr = []
      arr.forEach((element) => {
        let ele = individualInfo.mapsId[element]
        if (ele) {
          _arr.push(ele)
        }
      })
      arr = _arr.join(',')
    }
  } else {
    arr = data.groupConcatIds
  }
  return arr
}
function getNotSame(arr1, arr2) {
  return [...new Set(arr1)].filter((item) => !arr2.includes(item))
}

async function selectedProductDetails(data) {
  //个体返回
  if (data.details && data.details.length) {
    tableInfo.map.set(data.key, data)
    let index = tableInfo.data.findIndex((item) => item.key === data.key)
    if (index !== -1) {
      tableInfo.data[index] = data
    }
  } else {
    removeProduct(data)
  }
}
function getMain() {
  getWithTableRecordOrderById(props.orderId).then((resp) => {
    if (resp && resp.success) {
      formInfo.data = resp.data
    }
  })
  filterInfo.query.queryMap.orderId.value = props.orderId
  setBusinessDate()
  getList()
}
let flag = ref(true)
function getList() {
  //修改请求明细信息

  getWithTableRecordOrderDetailAll(filterInfo.query).then((resp) => {
    if (resp && resp.success && resp.data.length) {
      let data = resp.data
      data.forEach((item) => {
        //将返回的数据变成Map形式
        let key = []
        tableInfo.sysGroup.forEach((row) => {
          let obj = {}
          obj.columnName = row.columnName
          obj.asTbName = row.asTbName
          obj.value = item[row.key]
          if (row.key === 'batchNumber') {
            obj.value = item['oldBatchNumber']
          }
          if (row.key === 'validityDate') {
            obj.value = item['oldValidityDate']
          }
          if (row.key === 'productionDate') {
            obj.value = item['oldProductionDate']
          }
          key.push(obj)
        })
        item.key = JSON.stringify(key)
        if (!tableInfo.isSysGroup) {
          item.groupConcatDepotStockIds = item.depotStockId.toString()
          item.groupSize = 1
          let row = proxy.$fn.deepClone(item)
          delete row.key
          item.details = [row]
        }
        tableInfo.map.set(item.key, item)
      })

      if (flag.value) {
        flag.value = false
        data.forEach((element) => {
          let map = {}
          let groupConcatDepotStockIds =
            element.groupConcatDepotStockIds.split(',')
          let groupConcatIds = element.groupConcatIds.split(',')
          groupConcatDepotStockIds.forEach((element, index) => {
            individualInfo.mapsId[element] = groupConcatIds[index]
            individualInfo.mapsIdReversal[groupConcatIds[index]] = element
            map[element] = groupConcatIds[index]
          })
          element['mapKey'] = map
        })
      }
      tableInfo.data = data
    }
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function saveAndSubmit() {
  save(true)
}
function save(isSaveAndSubmit) {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let newDetails = tableInfo.data.filter(
      (row) => row.productId && row.calcQty > 0
    )
    if (!newDetails.length) {
      proxy.$message({
        message: '请添加有效的产品',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    let details = proxy.$fn.filterBlacklist(newDetails)
    let data = formInfo.data
    data.mergeDetails = details
    let api = props.orderId
      ? updateWithTableRecordOrder
      : isSaveAndSubmit === true ? createWithTableRecordOrderAndSave : createWithTableRecordOrder
    api(data).then((res) => {
      if (res && res.success) {
        showDialog.value = false
        emit('returnModify')
      }
    })
  })
}
//选择库存产品
const detailId = ref('')
function addProduct() {
  let keys = [...tableInfo.map.keys()]
  let excludeQueryList = []
  if (keys.length && tableInfo.sysGroup.length) {
    excludeQueryList = keys.map((item) => JSON.parse(item))
  }
  /* let arr = []
  Object.values(deleteRows.value).forEach((element) => {
    let ids = element.groupConcatIds.split(',')
    arr = arr.concat(ids)
  })
  arr = arr.join(',') */
  selectDepotStorageInfo.query.queryParams.detailId = detailId.value
  selectDepotStorageInfo.excludeQueryList = excludeQueryList //库存产品左侧过滤配置
  selectDepotStorageInfo.visible = true
}
async function selectDepotStorageCallBack(rows) {
  //库存产品返回
  await rows.forEach((item) => {
    item.oldBatchNumber = proxy.$fn.deepClone(item.batchNumber)
    item.oldValidityDate = proxy.$fn.deepClone(item.validityDate)
    item.oldProductionDate = proxy.$fn.deepClone(item.productionDate)
  })
  let map = await proxy.$fn.getDepotStorage(
    rows,
    tableInfo.sysGroup,
    tableInfo.map,
    getWithTableRecordOrderDetailAll, //个体弹窗右边数据接口
    props.orderId,
    individualInfo.rightVo, //个体弹窗右边表格配置
    'availableCalcQty',
    'depotStockId'
  )
  tableInfo.map = map
  tableInfo.data = [...map.values()]
  console.log(tableInfo.data)
}
const deleteRows = ref({})
watch(
  () => deleteRows.value,
  (val) => {
    let arr = []
    Object.values(val).forEach((element) => {
      let ids = element.groupConcatIds.split(',')
      arr = arr.concat(ids)
    })
    detailId.value = arr.join(',')
  },
  { deep: true }
)
//删除产品
function removeProduct(row = undefined) {
  if (row && row.key) {
    tableInfo.data = tableInfo.data.filter((item) => item.key !== row.key)
    deleteRows.value[row.id] = row
    let key = row.key
    tableInfo.map.delete(key)
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.selections.forEach((row) => {
          deleteRows.value[row.id] = row
          for (let [key, value] of tableInfo.map) {
            if (key === row.key) {
              tableInfo.map.delete(key)
            }
          }
        })
        tableInfo.data = tableInfo.data.filter((row) => {
          return !tableInfo.selections.includes(row)
        })
      })
  }
}
function getCustomize() {
  let param = {
    tableKey:
      'withTableRecordOrderModifyByAccept-com.slip.spd.entity.vo.withtable.WithTableRecordOrderDetailVO',
  }
  tableInfo.isSysGroup = false
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          tableInfo.isSysGroup = true
        }
      }
      filterInfo.query.customizeUserVO = data
      getDeoptLeftCustomize()
    }
  })
}
function getDeoptLeftCustomize() {
  //库存产品弹窗左侧配置

  let param = {
    tableKey:
      'withTableRecordOrderModifyQueryProductLeft-com.slip.spd.entity.vo.withtable.WithTableAcceptOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      let arr = []
      let obj = {}
      if (tableInfo.isSysGroup) {
        for (let key in data.detail) {
          if (data.detail[key].sysGroupLevel > 0) {
            arr.push({
              columnName: data.detail[key].columnName,
              asTbName: data.detail[key].asTbName,
              key: key,
            })
            obj[key] = {
              queryType: 'EQUALS',
              queryCategory: 'AND',
              ignoreEmptyValue: false,
              value: null,
            }
          }
        }
      } else {
        arr.push({
          columnName: data.detail.id.columnName,
          asTbName: data.detail.id.asTbName,
          key: 'depotStockId',
        })
        obj['depotStockId'] = {
          queryType: 'EQUALS',
          queryCategory: 'AND',
          value: null,
        }
      }
      scanInfo.query.customizeUserVO = data
      individualInfo.selectObj = obj
      tableInfo.sysGroup = arr
      if (props.orderId) {
        getMain()
      } else {
        setBusinessDate()
      }
    }
  })
}
function getInvdividualRightCustomize() {
  //获取个体弹窗右边配置
  let param = {
    tableKey:
      'withTableRecordOrderModifyByAccepSingleRight-com.slip.spd.entity.vo.withtable.WithTableRecordOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      individualInfo.rightVo = res.data
    }
  })
}
</script>

<style scoped lang="scss">
:deep(.page-table > .el-table) {
  overflow: hidden;
}
</style>
